# 键盘控制rect方向, 按一次一直动, 抬起按键停止
import pygame
import sys

from pygame_test.pygame_05_random_rect_01 import random_rect

pygame.init()

winx = 300
winy = 300
screen = pygame.display.set_mode((winx, winy))
BLACK = 0, 0, 0
WHITE = 255, 255, 255
r1_x = 100
r1_y = 100
speedx = 5  # cspeedx/y 当前speed
speedy = 5
cspeedx = 0
cspeedy = 0
fclock = pygame.time.Clock()

while True:
    screen.fill(BLACK)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        # 按下键盘

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                cspeedy = -speedy
                # 限制斜方向的运动
                cspeedx = 0
            elif event.key == pygame.K_DOWN:
                cspeedy = speedy
                cspeedx = 0
            elif event.key == pygame.K_LEFT:
                cspeedx = -speedx
                cspeedy = 0
            elif event.key == pygame.K_RIGHT:
                cspeedx = speedx
                cspeedy = 0
        if event.type == pygame.KEYUP:
            event_key = event.key
            # cspeedx = 0
            # cspeedy = 0
            # 如果横向的方向键抬起, 只停止横方向的运动
            if event_key == pygame.K_RIGHT or event_key == pygame.K_LEFT:
                cspeedx = 0
            elif event_key == pygame.K_UP or event_key == pygame.K_DOWN:
                cspeedy = 0

    r1_x += cspeedx
    r1_y += cspeedy
    r1 = r1_x, r1_y, 50, 50
    pygame.draw.rect(screen, WHITE, r1)
    random_rect(screen,10)
    pygame.display.update()
    fclock.tick(20)
